package com.zonda.sampleretrofit2.data;

import android.util.JsonReader;
import android.util.Log;

import com.zonda.sampleretrofit2.Contants;
import com.zonda.sampleretrofit2.model.AppBasicObject;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

public class AppResponseBodyConverter<T extends AppBasicObject> implements Converter<ResponseBody, T> {

  public final Type returnType;

  public AppResponseBodyConverter(Type returnType) {
    this.returnType = returnType;
  }

  @SuppressWarnings("unchecked")
  @Override
  public T convert(ResponseBody value) throws IOException {

//    Type mySuperClass = getClass().getGenericSuperclass();
//
//    Log.i(Contants.LOG_TAG, "mySuperClass : " + mySuperClass.getClass().getName());
//
//    Type[] genericInterfaces = AppResponseBodyConverter.class.getGenericInterfaces();
//    for (Type genericInterface : genericInterfaces) {
//      if (genericInterface instanceof ParameterizedType) {
//        Type[] genericTypes = ((ParameterizedType) genericInterface).getActualTypeArguments();
//        for (Type genericType : genericTypes) {
//          System.out.println("Generic type: " + genericType.getClass().getName());
//        }
//      }
//    }
//
//   if( ParameterizedType.class.isAssignableFrom(mySuperClass.getClass())){
//     Type[] actualTypeArguments = ((ParameterizedType) mySuperClass).getActualTypeArguments();
//     for (Type type :
//         actualTypeArguments) {
//       Log.i(Contants.LOG_TAG, "type : " + type.getClass().getName());
//     }
//   }

    Log.i(Contants.LOG_TAG, "returnType : " + returnType.toString());
    long startTime, endTime;
    try {
      startTime = System.currentTimeMillis();
      Log.i(Contants.LOG_TAG,"newInstance resume startTime: " + startTime);
      final T obj = ((Class<T>)returnType).newInstance();
      endTime = System.currentTimeMillis();
      Log.i(Contants.LOG_TAG,"newInstance resume endTime: " + endTime);
      Log.i(Contants.LOG_TAG,"newInstance resume time: " + (endTime - startTime));
      final JsonReader jsonReader = new JsonReader(value.charStream());
      obj.convertFrom(jsonReader);
      return obj;
    } catch (InstantiationException e) {
      e.printStackTrace();
    } catch (IllegalAccessException ignored) {
      Log.i(Contants.LOG_TAG,"" + ignored.getMessage());
    }
    return null;
  }

}
